# -*- coding = utf-8 -*-
# @Time : 2020/7/20 17:04
# @Author : gxm
'''


import urllib.request
import urllib.parse
import base64
import json
import time

# client_id 为官网获取的AK， client_secret 为官网获取的SK
client_id =	'iE29YFprzEcKmxntojlAUs0W'
client_secret ='WO4RNNVKbF5sRPpWGKSHXKAVoqdKbVuR'

# 获取token
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urllib.request.urlopen(request)
    token_content = response.read()
    # print (token_content)
    if token_content:
        token_info = json.loads(token_content)
        token_key = token_info['access_token']
    return token_key


# 画出驾驶行为识别结果
def driver_result(originfilename, persons, resultfilename, fontsize, fontcolor):
    from PIL import Image, ImageDraw, ImageFont

    image_origin = Image.open(originfilename)
    draw = ImageDraw.Draw(image_origin)
    setFont = ImageFont.truetype('C:/windows/fonts/simfang.ttf', fontsize)
    for person in persons:
        warning = ''
        result = ''
        attributes = person['attributes']
        # 使用手机
        score = attributes['cellphone']['score']
        threshold = attributes['cellphone']['threshold']
        if score > threshold:
            warning = warning + '使用手机 '
        result = result + ('使用手机： {:.5f} \n'.format(score))
        # 抽烟
        score = attributes['smoke']['score']
        threshold = attributes['smoke']['threshold']
        if score > threshold:
            warning = warning + '抽烟 '
        result = result + ('抽烟： {:.5f} \n'.format(score))
        # 未系安全带
        score = attributes['not_buckling_up']['score']
        threshold = attributes['not_buckling_up']['threshold']
        if score > threshold:
            warning = warning + '未系安全带 '
        result = result + ('未系安全带： {:.5f} \n'.format(score))
        # 双手离开方向盘
        score = attributes['both_hands_leaving_wheel']['score']
        threshold = attributes['both_hands_leaving_wheel']['threshold']
        if score > threshold:
            warning = warning + '双手离开方向盘 '
        result = result + ('双手离开方向盘： {:.5f} \n'.format(score))
        # 视角未看前方
        score = attributes['not_facing_front']['score']
        threshold = attributes['not_facing_front']['threshold']
        if score > threshold:
            warning = warning + '视角未看前方 '
        result = result + ('视角未看前方： {:.5f} \n'.format(score))

        gesture = person['location']
        draw.rectangle(
            (gesture['left'], gesture['top'], gesture['left'] + gesture['width'], gesture['top'] + gesture['height']),
            outline="red")

        if warning == '':
            warning = '无'
        result = result + '需要警告内容：' + warning
        print(result)
        draw.text((gesture['left'], gesture['top']), result, font=setFont, fill=fontcolor)

    image_origin.save(resultfilename, "JPEG")


# 驾驶行为识别
# filename:原图片名（本地存储包括路径）
def driver_behavior(filename, resultfilename, fontsize, color):
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior"
    print(filename)
    # 二进制方式打开图片文件
    f = open(filename, 'rb')
    img = base64.b64encode(f.read())

    params = dict()
    params['image'] = img
    # params = {'image': img}
    params = urllib.parse.urlencode(params).encode("utf-8")
    # params = json.dumps(params).encode('utf-8')

    access_token = get_token()
    begin = time.perf_counter()
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = urllib.request.urlopen(request)
    content = response.read()
    end = time.perf_counter()

    print('处理时长:' + '%.2f' % (end - begin) + '秒')
    if content:
        # print(content)
        content = content.decode('utf-8')
        # print(content)
        data = json.loads(content)
        print('人数:', data['person_num'])
        # print(data)
        result = data['person_info']

        driver_result(filename, result, resultfilename, fontsize, color)

if __name__ == '__main__':
    driver_behavior('C:\\Users\\19372\\Desktop\\98.jpg', 'C:\\Users\\19372\\Desktop\\98_result.jpg', 20, 'blue')

'''

import requests
import base64


# client_id 为官网获取的AK， client_secret 为官网获取的SK
client_id =	'iE29YFprzEcKmxntojlAUs0W'
client_secret ='WO4RNNVKbF5sRPpWGKSHXKAVoqdKbVuR'
'''
驾驶行为分析
'''


api = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials' \
              '&client_id={}&client_secret={}'.format(client_id, client_secret)

rp = requests.post(api)
rp_json = rp.json()
print(rp_json['access_token'])




def weixianjiashixingwei(path):
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior"
    f = open(path, 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img}
    access_token = rp_json['access_token']
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        print(response.json())
        persons = response.json()["person_info"]
        for person in persons:
            warning = ''
            result = ''
            attributes = person['attributes']
            # 使用手机
            score = attributes['cellphone']['score']
            threshold = attributes['cellphone']['threshold']
            if score > threshold:
                warning = warning + '使用手机 '
            result = result + ('使用手机： {:.5f} \n'.format(score))
            # 抽烟
            score = attributes['smoke']['score']
            threshold = attributes['smoke']['threshold']
            if score > threshold:
                warning = warning + '抽烟 '
            result = result + ('抽烟： {:.5f} \n'.format(score))
            # 未系安全带
            score = attributes['not_buckling_up']['score']
            threshold = attributes['not_buckling_up']['threshold']
            if score > threshold:
                warning = warning + '未系安全带 '
            result = result + ('未系安全带： {:.5f} \n'.format(score))
            # 双手离开方向盘
            score = attributes['both_hands_leaving_wheel']['score']
            threshold = attributes['both_hands_leaving_wheel']['threshold']
            if score > threshold:
                warning = warning + '双手离开方向盘 '
            result = result + ('双手离开方向盘： {:.5f} \n'.format(score))
            # 视角未看前方
            score = attributes['not_facing_front']['score']
            threshold = attributes['not_facing_front']['threshold']
            if score > threshold:
                warning = warning + '视角未看前方 '
            result = result + ('视角未看前方： {:.5f} \n'.format(score))
            # 闭眼
            score = attributes['eyes_closed']['score']
            threshold = attributes['eyes_closed']['threshold']
            if score > threshold:
                warning = warning + '闭眼 '
            result = result + ('闭眼： {:.5f} \n'.format(score))
            # 没带口罩
            score = attributes['no_face_mask']['score']
            threshold = attributes['no_face_mask']['threshold']
            if score > threshold:
                warning = warning + '没带口罩 '
            result = result + ('没带口罩： {:.5f} \n'.format(score))


            print(warning)
            print(result)
    return warning


if __name__ == "__main__":
    weixianjiashixingwei('C:\\Users\\19372\\Desktop\\89.png')